<template>
  <div class="container">
    <div class="search-form">
      <el-form :model="formUser" inline label-width="100px">
        <el-form-item label="用户姓名">
          <el-input v-model="formUser.name" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectUser()">查询</el-button>
          <el-button type="primary" @click="selectUser('rest')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <el-table :data="dangqiandata" stripe border>
        <el-table-column prop="UserID" label="用户ID" align="center"></el-table-column>
        <el-table-column prop="UserName" label="用户姓名" align="center"></el-table-column>
        <el-table-column prop="UserAccount" label="用户账号" align="center"></el-table-column>
        <el-table-column prop="UserPWD" label="用户密码" align="center"></el-table-column>
        <el-table-column prop="UserPhone" label="用户手机号" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="250">
          <template #default="scope">
            <el-button link type="primary" @click="delUser(scope.row.UserID)">删除</el-button>
            <el-button link type="primary" @click="updateUser(scope.row)">修改</el-button>
            <el-button link type="primary" @click="viewUserDetails(scope.row)">查看相关</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="currentPage" :page-size="5" :total="userList.length" class="pagination"></el-pagination>
    </div>
  </div>

  <!-- 修改用户信息弹窗 -->
  <el-dialog v-model="dialogUpdateFormVisible" title="修改用户信息" width="500">
    <el-form :model="formUpdate">
      <el-form-item label="用户ID">
        <el-input disabled v-model="formUpdate.id" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户姓名">
        <el-input v-model="formUpdate.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户账号">
        <el-input v-model="formUpdate.account" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户密码">
        <el-input v-model="formUpdate.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户手机号">
        <el-input v-model="formUpdate.userphone" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogUpdateFormVisible = false">取消</el-button>
        <el-button type="primary" @click="querenxiugai"> 确认修改 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 查看用户详情弹窗 -->
  <el-dialog v-model="dialogViewDetailsVisible" title="用户详情" width="80%">
    <el-tabs type="border-card">
      <el-tab-pane label="用户博客">
        <el-table :data="userPosts" border stripe>
          <el-table-column label="标题" prop="PostTitle" align="left"></el-table-column>
          <el-table-column label="内容" prop="PostContent" align="left"></el-table-column>
          <el-table-column label="发布时间" prop="Post_Date" align="center" :formatter="formatDate"></el-table-column>
          <el-table-column label="更新时间" prop="Post_Update_Date" align="center" :formatter="formatDate"></el-table-column>
          <el-table-column label="浏览量" prop="Post_Views" align="center"></el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="用户评论">
        <el-table :data="userComments" border stripe>
          <el-table-column label="评论内容" prop="CommentContent" align="left"></el-table-column>
          <el-table-column label="评论时间" prop="Comment_Date" align="center" :formatter="formatDate"></el-table-column>
          <el-table-column label="所属博客" prop="PostTitle" align="center"></el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>
  
<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { getUserListApi, delUserListApi, updateUserListApi, getUserPostsApi, getUserCommentsApi } from '../api/userApi';
import { ElMessageBox, ElMessage } from 'element-plus';

// 表单数据
const formUser = reactive({
  name: '' // 用户姓名
});

// 用户列表数据
const userList = ref([]);

// 分页相关
const currentPage = ref(1);
const dangqiandata = computed(() => {
  return userList.value.slice((currentPage.value - 1) * 5, currentPage.value * 5);
});

// 修改用户对话框相关
const dialogUpdateFormVisible = ref(false);
const formUpdate = reactive({
  id: '',
  name: '',
  account: '',
  password: '',
  userphone: ''
});

const dialogViewDetailsVisible = ref(false); // 查看用户详情弹窗
const userPosts = ref([]); // 用户博客数据
const userComments = ref([]); // 用户评论数据

// 查询用户列表
const selectUser = (rest) => {
  if (rest === 'rest') {
    formUser.name = ''; // 重置查询条件
  }
  getUserListApi(formUser).then(res => {
    if (res.status === 0) {
      userList.value = res.data; // 更新用户列表
    } else {
      ElMessage({
        type: 'error',
        message: '获取用户列表失败'
      });
    }
  });
};

// 初始化加载用户列表
onMounted(() => {
  selectUser();
});

// 删除用户
const delUser = id => {
  ElMessageBox.confirm('是否要删除这个用户', 'Warning', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delUserListApi(id).then(resp => {
        if (resp.status === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          });
          selectUser(); // 重新加载用户列表
        } else {
          ElMessage({
            type: 'error',
            message: resp.msg || '删除失败'
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      });
    });
};

// 打开修改用户对话框
const updateUser = userItem => {
  dialogUpdateFormVisible.value = true;
  Object.assign(formUpdate, {
    id: userItem.UserID, // 确保字段名与后端一致
    name: userItem.UserName,
    account: userItem.UserAccount,
    password: userItem.UserPWD,
    userphone: userItem.UserPhone
  });
};
// 确认修改用户信息
const querenxiugai = () => {
  updateUserListApi(formUpdate.id, formUpdate).then(resp => {
    if (resp.status === 0) {
      ElMessage({
        type: 'success',
        message: '修改成功'
      });
      dialogUpdateFormVisible.value = false;
      selectUser(); // 重新加载用户列表
    } else {
      ElMessage({
        type: 'error',
        message: resp.msg || '修改失败'
      });
    }
  });
};


// 查看用户详情
const viewUserDetails = (user) => {
  const UserID = user.UserID; // 从 user 对象中提取 UserID
  console.log('查看用户详情 ID:', UserID); // 打印日志

  // 获取用户博客
  getUserPostsApi(UserID).then(res => {
    if (res.status === 0) {
      userPosts.value = res.data; // 更新用户博客数据
    } else {
      ElMessage({
        type: 'error',
        message: '获取用户博客失败'
      });
    }
  });

  // 获取用户评论
  getUserCommentsApi(UserID).then(res => {
    if (res.status === 0) {
      userComments.value = res.data; // 更新用户评论数据
    } else {
      ElMessage({
        type: 'error',
        message: '获取用户评论失败'
      });
    }
  });


  // 打开查看详情弹窗
  dialogViewDetailsVisible.value = true;
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '-';
  const date = new Date(cellValue);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

</script>


<style scoped>
.container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 20px;
}

.el-button {
  margin-right: 10px;
}

.el-dialog {
  border-radius: 8px;
}

.el-tabs {
  margin-top: 20px;
}
</style>
  